package serveur;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.ArrayList;
import java.sql.*;
import data.*;

public class ServeurCentralUDP 
{	
	private final String AUTHENTIFICATION = "data.AuthentificationData";
	private final String CHAUFFAGE  = "data.Chauffage";
	private final String STORES = "data.Stores";
	private final String COLLECTIONITEMS = "data.CollectionItemData";
	private final String COLLECTIONPIECES = "java.util.ArrayList"; 
	private InetAddress destinationAdress = null;
	private int destinationPort = 0;
	private DatagramSocket socket = null;
	private int localPort = 32665;
	private String etat;
	private Connection connexionBdd;
	
	public ServeurUDP() 
	{
		try
	    {
		Connection connexion = DriverManager.getConnection("jdbc:mysql://localhost/domotique","root","Baltosss1989");
	    	socket = new DatagramSocket(localPort);
	    	socket.setSoTimeout(0); // receive bloquant jusqu'a r�ception d'un paquet
	    	etat = "stop";
	    }
	    catch(SocketException e) 
		{
			exit(1);		
		}
		catch(SQLException e)
		{
			exit(2);	
		}
	}
	
	public void startServeur()
	{
		etat = "run";
		System.out.println("D�marrage du serveur");
		Object data = new AuthentificationData();
		ArrayList <String> a = new ArrayList <String>();
		System.out.println(a.getClass().getName());
		if (data.getClass().getName().equals(AUTHENTIFICATION))
		{
			gestion((AuthentificationData)data);
		}
		else
		{
			System.out.println("GROS FAIL");
		}
		
		
		/*while(etat.equals("run"))
		{
			//data = receiveData();
			if (data.getClass().getName().equals(AUTHENTIFICATION))
			{
				
			}
		}*/
	}
	
	public void stopServeur()
	{
		etat = "stop";
	}
	
	public Object receiveData()
	{
		byte[] buffer = new byte[1024];
		DatagramPacket p = new DatagramPacket(buffer, buffer.length);
		try
		{
			socket.receive(p);
		}
		catch(IOException e)
		{
			return null;
		}
		
		destinationAdress = p.getAddress(); //on r�cup�re l'adresse de l'�metteur du paquet
		destinationPort = p.getPort(); // on r�cup�re le port de l'�metteur du paquet
		
		ByteArrayInputStream input = new ByteArrayInputStream(buffer);
		try
		{
			ObjectInputStream oos = new ObjectInputStream(input);
			try
			{
				return oos.readObject();
			}
			catch (IOException e)
			{
				return null;
			}
			catch(ClassNotFoundException e) 
			{
				return null;
			}
			finally
			{
				oos.close();
				input.close();
			}
		}
		catch(IOException e)
		{
			return null;
		}		
	}
	
	public int sendData(Object tosend)
	{	
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		try
		{
			ObjectOutputStream oos = new ObjectOutputStream(output);
			try
			{
				oos.writeObject(tosend);
			}
			catch (IOException e)
			{
				oos.close();
				output.close();
			}
		}	
		catch (IOException e)
		{
			return -1;
		}
		
		DatagramPacket p = new DatagramPacket(output.toByteArray(), output.toByteArray().length, destinationAdress, destinationPort);
		try
		{		
			socket.send(p);
		}
		catch(IOException e)
		{
			return -1;
		}
		return 0;
	}

	/*gestion(AuthentificationData) : fonction utilisée par le serveur central. 
	 *Il faut rajouter les paramètres de connexion nécessaire au client vers le serveur foyer pour qu'il puisse se connecter ensuite. 
	 */
	public AuthentificationData gestion(AuthentificationData data)
	{
		//travail a effectuer :
		//comparer data.getLogin() et data.getPasswor() avec la base de donn�es
		try
		{
			Statement stmt = connexionBdd.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
			ResultSet rs = stmt.executeQuery("SELECT * FROM utilisateur WHERE login="+data.getLogin()+" AND password = "+data.getPassword());
			//si ok faire data.setResult(1)
			if(rs.getFetchSize()>0)
			{
				rs.next();
				data.setResult(1);
				data.setNumPort(rs.getInt("NumPort"));
				data.setAdrIp(rs.getString("AdresseIP"));
			}
			//sinon data.setResult(0)
			else
			{
				data.setResult(0);
			}
		}
		catch(SQLException e)
		{
			//On peut aussi faire : data.setResult(0); return data;
			return null;
		}
		return data;
	}
}
